package com.projectsexception.festivales;

import java.net.MalformedURLException;
import java.net.URL;
import java.util.Iterator;
import java.util.List;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.SubMenu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

import com.projectsexception.festivales.news.FeedLoadingTask;
import com.projectsexception.festivales.news.FeedTaskActivity;
import com.projectsexception.festivales.news.model.Feed;
import com.projectsexception.festivales.news.view.FeedEntryAdapter;
import com.projectsexception.festivales.setup.FeedInfo;
import com.projectsexception.festivales.setup.ProjectResources;

public class TabNewsActivity extends Activity implements FeedTaskActivity {
    
    private static final String ACTUAL_FEED = "actualFeed";
    
    private Integer actualFeed;
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.tab_news);        
    }
    
    @Override
    protected void onResume() {
        super.onResume();
        SharedPreferences settings = getSharedPreferences(getString(R.string.app_name), MODE_PRIVATE);
        if (settings.contains(ACTUAL_FEED)) {
            actualFeed = settings.getInt(ACTUAL_FEED, 0);
        } else {
            List<FeedInfo> feeds = ProjectResources.getInstance().getFeeds();
            actualFeed = feeds.get(0).getId();
        }
        loadActualFeed();
    }
    
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.tab_news_menu, menu);
        SubMenu subMenu = menu.findItem(R.id.tab_news_menu_change).getSubMenu();
        List<FeedInfo> feeds = ProjectResources.getInstance().getFeeds();
        for (FeedInfo feed : feeds) {
            subMenu.add(R.id.tab_news_menu_change, feed.getId(), 0, feed.getName());
        }
        return true;
    }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == R.id.tab_news_menu_refresh) {
            ProjectResources.getInstance().deleteAllFeedCache();
            loadActualFeed();
        } else if (item.getGroupId() == R.id.tab_news_menu_change) {
            if (actualFeed != item.getItemId()) {
                actualFeed = item.getItemId(); 
                loadActualFeed();
            }            
        }
        return true;
    }
    
    @Override
    protected void onPause() {
        super.onPause();
        Editor editor = getSharedPreferences(getString(R.string.app_name), MODE_PRIVATE).edit();
        editor.putInt(ACTUAL_FEED, actualFeed);
        editor.commit();
    }

    @Override
    public void feedLoaded(final Feed feed) {
        if (feed != null) {
            ProjectResources.getInstance().saveFeedCache(feed);
        }
        updateView(feed);
    }

    @Override
    public void loadingFeed() {
        Toast.makeText(getBaseContext(), getString(R.string.tab_news_loading), Toast.LENGTH_SHORT).show();
        View progress = findViewById(R.id.progress);
        progress.setVisibility(View.VISIBLE);
    }
    
    private void updateView(final Feed feed) {
        TextView feedtitle = (TextView) findViewById(R.id.feed);
        
        if (feed == null) {
            feedtitle.setText(getString(R.string.tab_news_unavailable));
        } else {
            feedtitle.setText(feed.getTitle());
            ListView listView = (ListView) findViewById(R.id.entry_list);
            listView.setAdapter(new FeedEntryAdapter(this, feed));
            
            listView.setOnItemClickListener(new OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> adapter, View view, int position, long id) {
                    Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse(feed.getEntryList().get(position).getLink()));
                    startActivity(i);
                }
            });
        }
        View progress = findViewById(R.id.progress);
        progress.setVisibility(View.INVISIBLE);        
    }
    
    private void loadActualFeed() {
        Feed feed = ProjectResources.getInstance().loadFeedCache(actualFeed);
        
        if (feed != null) {     
            updateView(feed);
        } else {        
            FeedInfo feedInfo = getActualFeedInfo();
            if (feedInfo != null) {
                try {
                    URL feedURL = new URL(feedInfo.getLink());
                    new FeedLoadingTask(this).execute(feedURL);
                } catch (MalformedURLException e) {
                    Log.e("TabNewsActivity", e.getMessage());
                }
            }
        }
    }
    
    private FeedInfo getActualFeedInfo() {
        FeedInfo feedInfo;
        for (Iterator<FeedInfo> it = ProjectResources.getInstance().getFeeds().iterator(); it.hasNext();) {
            feedInfo = it.next();
            if (feedInfo.getId() == actualFeed) {
                return feedInfo;
            }            
        }
        return null;
    }
}
